package com.fengye.common.utils;

import com.fengye.common.constants.CommonConstant;
import org.apache.commons.lang3.StringUtils;

import jakarta.servlet.http.HttpServletRequest;

/**
 * @author sunlei
 * @version 1.0
 * @date 2024/8/13 15:26:31
 * @description 从请求中获取bearer token
 */
public class TokenExtractorUtils {
    /**
     * 获取请求头中去除Bearer前缀的token，返回值可能为null
     *
     * @param request 请求对象
     * @return token
     */
    public static String getHeaderBearerToken(HttpServletRequest request) {
        String token = null;
        // 获取请求头中的bearer开头的token
        String bearerToken = request.getHeader(CommonConstant.HTTP_HEADER_BEARER_KEY);
        if (StringUtils.isNotBlank(bearerToken) &&
                bearerToken.startsWith(CommonConstant.HTTP_HEADER_BEARER_TOKEN_PREFIX) &&
                bearerToken.length() > CommonConstant.HTTP_HEADER_BEARER_TOKEN_PREFIX.length()) {
            token = bearerToken.substring(CommonConstant.HTTP_HEADER_BEARER_TOKEN_PREFIX.length());
        }
        return token;
    }
}
